package com.dferreira.languagesteach.data_adapters;

import android.content.Context;
import android.util.Log;
import android.view.View;

import com.dferreira.languagesteach.LanguagesTeachApplication;
import com.dferreira.languagesteach.activities.generic.IFragmentStack;
import com.dferreira.languagesteach.constants.Constants;
import com.dferreira.languagesteach.custom_items.UITableViewCell;
import com.dferreira.languagesteach.data_models.MetaLesson;
import com.dferreira.languagesteach.data_parsers.XMLLanguageParser;
import com.dferreira.languagesteach.data_adapters.generic.NavigationAdapter;
import com.dferreira.languagesteach.fragments.SubjectsFragment;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Iterator;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * Parses the language.xml file and provide ways access to his information
 *
 * @author dferreira
 */
public class LessonsAdapter extends NavigationAdapter {

    private final String TAG = "LessonsAdapter";


    /**
     * @param context reference to the which the dataSource belongs
     */
    public LessonsAdapter(Context context, IFragmentStack fragmentStack, String packageInstalledFolder) {
        super(context, packageInstalledFolder);
        setFragmentStack(fragmentStack);
    }

    /**
     * @return false   -> some error happened
     * true    -> everything was alright
     */
    public boolean buildDataSet() {
        Iterator<MetaLesson> lessons;

        lessons = parseLanguageXML();

        if (lessons == null) {
            return false;
        }
        // Build from LanguageCells
        buildLessonsList(lessons);
        dataSetWellConstructed();
        return true;
    }

    /**
     * Parse the language.xml file from some package
     *
     * @return an level iterator
     */
    private Iterator<MetaLesson> parseLanguageXML() {
        // Local variables
        SAXParserFactory spf;
        SAXParser sp;
        XMLReader xr;
        XMLLanguageParser xmlLanguageParser;
        InputStream inputStream;
        File file;
        String languageFileName;

        languageFileName = Constants.LANGUAGE_FILE_NAME;
        try {
            // parsing from XML file
            spf = SAXParserFactory.newInstance();
            sp = spf.newSAXParser();
            xr = sp.getXMLReader();
            xmlLanguageParser = new XMLLanguageParser();
            xr.setContentHandler(xmlLanguageParser);
            file = new File(getPackageInstalledFolder() + File.separator
                    + languageFileName);
            inputStream = new FileInputStream(file);
            xr.parse(new InputSource(inputStream));
            inputStream.close();

            return xmlLanguageParser.getMetaLessons().iterator();
        } catch (FileNotFoundException fException) {
            Log.e(TAG, TAG, fException);
        } catch (Exception genericException) {
            Log.e(TAG, TAG, genericException);
        }
        return null;
    }

    /**
     * Build from Lesson Cells
     *
     * @param metaLessons models available the language.xml
     */
    private void buildLessonsList(Iterator<MetaLesson> metaLessons) {
        while (metaLessons.hasNext()) {
            UITableViewCell tmpCell;
            MetaLesson metaLesson = metaLessons.next();
            tmpCell = new UITableViewCell();
            tmpCell.setTextLabel(metaLesson.getTitle());
            tmpCell.setTag(metaLesson.getFolder());
            add(tmpCell);
        }
    }

    /**
     */
    private void pushSubjectsFragment() {
        SubjectsFragment subjectsFragment = new SubjectsFragment();
        subjectsFragment.setArguments(getPackageInstalledFolder(), getFragmentStack());
        getFragmentStack().pushFragment(subjectsFragment);
    }

    /**
     * Handle a click from a level
     *
     * @param v view of the level pressed
     */
    @Override
    public void onClick(View v) {
        String lessonTag;
        lessonTag = (String) v.getTag();
        LanguagesTeachApplication.getApplicationState().setLessonFolder(lessonTag);
        pushSubjectsFragment();
    }
}